package cn.ad.server.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author dongbin.yu
 * @from 2016-05-24
 * @since V1.0
 */
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {

        synchronized (SpringContextUtils.class) {
            SpringContextUtils.applicationContext = applicationContext;
        }
    }

    public static Object getBean(String name) {

        Object bean = applicationContext.getBean(name);

        if(bean == null){
            logger.info("bean name {} is not exists", name);
        }

        return bean;
    }

    public static <T> T getBean(String name, Class<T> clazz) {

        T bean = applicationContext.getBean(name, clazz);

        if(bean == null){
            logger.info("bean name {} is not exists", name);
        }

        return bean;
    }

    public static <T> T getBean(Class<T> clazz) {

        T bean = applicationContext.getBean(clazz);

        if(bean == null){
            logger.info("bean name {} is not exists", clazz.getSimpleName());
        }

        return bean;
    }
}
